<template>
    <view class="container">
        <view class="form">
            <view class="form-item">
                <view class="label">声音名称</view>
                <u-input
                    border="null"
                    placeholder="请输入声音名称"
                    v-model="title"
                ></u-input>
            </view>
        </view>
        <view class="upload-wrap">
            <view @tap="uploadAudio" class="upload-box default" v-if="!uploadObj.status">
                <image mode="widthFix" src="/static/clone/ic_upload_voice.png"></image>
                <!-- #ifdef MP-WEIXIN -->
                <view class="text">从微信聊天选择音频文件</view>
                <!-- #endif -->
                <!-- #ifndef MP-WEIXIN -->
                <view class="text">上传文件</view>
                <!-- #endif -->
            </view>
            <view class="upload-box success" v-if="uploadObj.url && uploadObj.status === 'success'">
                <view class="play-btn">
                    <view @tap="clearUploadObj" class="close">
                        <u-icon name="close-circle-fill" :size="24"></u-icon>
                    </view>
                    <image
                        @tap="soundPlay('pause')"
                        mode="widthFix"
                        src="/static/clone/pause-white.png"
                        v-if="audio"
                    ></image>
                    <image
                        @tap="soundPlay()"
                        mode="widthFix"
                        src="/static/clone/play-white.png"
                        v-else
                    ></image>
                </view>
                <image class="cover" mode="aspectFill" src="/static/clone/player_bg.jpg"></image>
            </view>
            <view class="upload-box" v-if="uploadObj.status && uploadObj.status === 'loading'">
                <view class="upload-status">
                    <view class="proress">{{ '' + uploadObj.progress + '%' }}</view>
                    <view>上传中</view>
                </view>
            </view>
            <view class="upload-box fail" v-if="uploadObj.status && uploadObj.status === 'fail'">
              <view class="play-btn">
                <view @tap="clearUploadObj" class="close">
                  <u-icon name="close-circle-fill" :size="24"></u-icon>
                </view>
              </view>
              <view>上传失败</view>
            </view>
            <view class="rule-wrap">
                <view class="top">
                    <view class="label">声音录制要求</view>
                    <view @tap="goExamplePage" class="tips-icon">
                        <u-icon color="#999999" name="file-text" size="22"></u-icon>
                        <text class="text">录音文案示例</text>
                    </view>
                </view>
                <u-row
                    align="top"
                    customStyle="margin-top: 10px;border-bottom: 2rpx solid #F5F5F5;padding-bottom: 16rpx"
                    v-for="(item, index) in hintList"
                    :key="index"
                >
                    <u-col span="3">
                        <view class="desc-label">{{ item.title }}</view>
                    </u-col>
                    <u-col span="9">
                        <view class="desc-value">
                          <view v-for="text in item.content">{{ text }}</view>
                        </view>
                    </u-col>
                </u-row>
            </view>
        </view>
        <view class="button">
            <button @tap="confirm" class="confirm-btn" :plian="true">提交</button>
        </view>
        <protocol
            @close="protocolClose"
            ref="protocol"
        ></protocol>
    </view>
</template>

<script>
import protocol from '@/components/protocol'
export default {
  components: { protocol },
  data() {
    return {
      id: '',
      title: '',
      uploadObj: {
        url: ''
      },
      audio: null,
      hintList: [],
      fileTypes: ['mp3', 'MP3', 'm4a', 'M4A', 'wav', 'WAV', 'ogg', 'OGG', 'aac', 'AAC', 'ogg_opus', 'OGG_OPUS']
    };
  },
  onLoad(option) {
    this.getHintList()
  },
  onHide() {
    this.soundPlay('pause');
  },
  beforeDestroy() {
    this.soundPlay('pause');
  },
  deactivated() {
    this.soundPlay('pause');
  },
  methods: {
    protocolClose() {
      uni.navigateBack({
        fail: function () {
          uni.reLaunch({
            url: '/pages/index/index'
          })
        }
      });
    },
    getHintList() {
      this.$util.request({
        url: '/userVoice/getHintList'
      }).then(res => {
        var hintList = res.data
        hintList.forEach((item,index) => {
          hintList[index].content = item.content.split("\n");
        })
        this.hintList = hintList
      })
    },
    confirm() {
      this.soundPlay('pause');
      if (!this.title) {
        this.$util.message('请输入声音名称')
        return
      }
      if (!this.uploadObj.url) {
        this.$util.message('请上传声音文件')
        return
      }
      if (this.uploadObj.duration) {
        if (this.uploadObj.duration < 10) {
          this.$util.message('音频太短了，至少10s以上');
          return;
        }
        if (this.uploadObj.duration > 600) {
          this.$util.message('音频太长了，不要超过10分钟')
          return
        }
      }

      this.$util.request({
        url: '/userVoice/submit',
        data: {
          id: this.id || 0,
          title: this.title,
          duration: this.uploadObj.duration,
          audio_url: this.uploadObj.url,
          size: this.uploadObj.size
        },
        loadingText: '正在提交'
      }).then(res => {
        this.$util.message(res.message, 'success')
        setTimeout(() => {
          uni.switchTab({
            url: '/pages/clone/index?type=voice'
          })
        }, 1000);
      });
    },
    soundPlay(action = 'play') {
      if (action === 'play') {
        this.audio = uni.createInnerAudioContext();
        this.audio.autoplay = true;
        this.audio.src = this.uploadObj.url;
      } else if (action === 'pause') {
        try {
          if (this.audio) {
            this.audio.pause();
            this.audio.destroy();
          }
          this.audio = null;
        } catch (e) {
          console.log('soundPlay Pause', e);
        }
      }
    },
    clearUploadObj() {
      this.uploadObj = {
        url: '',
        title: '',
        size: '',
        duration: '',
        filePath: '',
        progress: 0,
        status: ''
      };
      this.soundPlay('pause');
    },
    uploadAudio() {
      var that = this;
      var data = {
        filePath: '',
        fileName: '',
        fileSize: 0
      };
      var chooseFunc = uni.chooseFile;
      if (uni.chooseMessageFile) {
        chooseFunc = uni.chooseMessageFile
      }
      chooseFunc({
        count: 1,
        type: 'file',
        extension: this.fileTypes,
        success: function (file) {
          data.filePath = file.tempFiles[0].path;
          data.fileSize = file.tempFiles[0].size;
          data.fileName = file.tempFiles[0].name;
          if (data.fileSize / 1024 / 1024 > 10) {
            setTimeout(() => {
              that.$util.message('请上传10M以内的文件')
            }, 500)
            return
          }
          that.uploadObj = {
            title: data.fileName,
            size: data.fileSize,
            filePath: data.filePath,
            progress: 0,
            duration: 0,
            status: 'loading'
          };
          that.$util.upload({
            url: '/userVoice/upload',
            filePath: data.filePath,
            name: 'audio',
            onProgressUpdate: function (res) {
              that.uploadObj.progress = res.progress;
            }
          }).then(res => {
            that.uploadObj.status = 'success';
            that.uploadObj.url = res.url;
            const audioContext = uni.createInnerAudioContext();
            audioContext.src = res.url;
            audioContext.onCanplay(() => {
              that.uploadObj.duration = Math.ceil(audioContext.duration)
            });
          }).catch(err => {
            that.clearUploadObj()
          })
        },
        fail: function (err) {
          console.log('选择文件失败：', err);
        }
      });
    },
    reUpload(e) {
      var that = this;
      this.uploadObj.status = 'loading';
      (0, s.upload)({
        fileList: [d({}, this.uploadObj)],
        onProgressUpdate: function (t, e) {
          that.uploadObj.progress = t.progress;
        },
        callback: function (e) {
          if (e.success) {
            that.uploadObj.status = 'success';
            that.uploadObj.url = e.resource_url;
            var o = uni.createInnerAudioContext();
            o.src = that.uploadObj.url;
            o.onCanplay(function (t) {
              console.log('onCanplay', o.duration);
            });
          } else {
            that.uploadObj.status = 'fail';
          }
        }
      });
    },
    goExamplePage() {
      uni.navigateTo({
        url: '/pages/clone/text-example'
      });
    }
  }
}

</script>
<style scoped>
@import './create-voice.css';
</style>
